<template>
  <div style="display: none;"></div>
</template>

<script lang="ts">
import { defineComponent, inject, onMounted, onUnmounted, ref } from 'vue'
import { useStore } from '@/store'
import { CesiumRef, CESIUM_REF_KEY } from '@/libs/cesium/cesium-vue'
import * as Cesium from 'cesium'
import axios from 'axios'
import { GeoJsonDataSource } from 'cesium';

interface TownshipData {
  [key: string]: number | unknown;
}

export default defineComponent({
  name: 'farmland-layer',
  setup() {
    let handler: Cesium.ScreenSpaceEventHandler | null = null;
    let dataSource: Cesium.GeoJsonDataSource | null = null;
    const store = useStore();
    const cesiumRef = inject<CesiumRef>(CESIUM_REF_KEY);
    let highlightEntity: Cesium.Entity | null = null;
    const townshipData = ref<TownshipData>({});

    let WellInfos: any[] = [];
    // 在全局或模块作用域中定义数据源
    let wellDataSource: Cesium.CustomDataSource;
    // 全局变量记录当前监听器
    let cameraListener: Cesium.Event.RemoveCallback | null = null;
    //机井二维码
    let QRblob: string | null = null;
    // 存储所有乡镇实体（用于后续恢复）
    let allEntities: any[] = [];
    // 存储所有村实体
    let villageEntities: Cesium.Entity[] = [];

    // 获取乡镇数据
    const fetchTownshipData = async () => {
      try {
        const response = await axios.get('/api/farmwell/well/centerMap?regionCode=411623');
        console.log(response.data)
        for (const [key, value] of Object.entries(response.data.data)) {
          townshipData.value[key] = value;
        }
      } catch (error) {
        console.error('获取乡镇数据失败:', error);
      }
    };

    // 颜色映射函数，根据数值(value)的分段范围映射颜色
    const getColor = (state: string, value: number, alpha: number): Cesium.Color => {
      // 定义数值分段对应的颜色（键为分段标识，值为颜色）
      const colorMap: Record<string, string> = {
        '0-49': '#00BFFF',    // value ≤ 50（包含50）
        '50-199': '#00BFFF',  // 51 ≤ value ≤ 200
        '200-599': '#00BFFF', // 201 ≤ value ≤ 600
        '600-999': '#00BFFF',// 601 ≤ value ≤ 1000
        '1000+': '#00BFFF',   // value > 1000
        'default': '#00BFFF'  // 默认颜色（处理异常值）
      };

      // 根据value计算对应的分段标识（state）
      let segment: string;
      if (value <= 49) {
        segment = '0-49';
      } else if (value <= 199) {
        segment = '50-199';
      } else if (value <= 599) {
        segment = '200-599';
      } else if (value <= 999) {
        segment = '600-999';
      } else {
        segment = '1000+';
      }

      // 获取分段对应的颜色，不存在时用默认色
      const baseColor = colorMap[segment] || colorMap['default'];

      return Cesium.Color.fromCssColorString(baseColor)
        .withAlpha(alpha);
    };

    // 创建动态材质
    const createLandMaterial = (entity: Cesium.Entity) => {
      return new Cesium.ColorMaterialProperty(
        new Cesium.CallbackProperty(() => {
          const isHovered = highlightEntity === entity;
          const state = entity.properties?.state?.getValue();
          const properties = entity.properties?.getValue();
          const rawName = properties?.name || '未命名地块';
          const townshipKey = rawName.trim().replace(/\s+/g, '');
          const value = townshipData.value[townshipKey] || 0;
          const numericValue = typeof value === 'number' ? value : 0; // 默认 0
          return getColor(state, numericValue, isHovered ? 1.0 : 0.5);
        }, false)
      );
    };

    // 加载乡镇名称GeoJSON方法
    const loadGeoJson = async (viewer: Cesium.Viewer) => {
      try {
        await fetchTownshipData(); // 获取乡镇数据
        interface CustomLoadOptions extends GeoJsonDataSource.LoadOptions {
          heightReference?: Cesium.HeightReference;
          clampToGround?: boolean;
        }

        const options: CustomLoadOptions = {
          stroke: Cesium.Color.TRANSPARENT,
          clampToGround: true,
          heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
          strokeWidth: 2
        };
        dataSource = await Cesium.GeoJsonDataSource.load('public/static/geojson/411623.json', options);

        viewer.dataSources.add(dataSource);

        dataSource.entities.values.forEach(entity => {
          if (entity.polygon) {
            // 保持原有样式设置
            entity.polygon.material = createLandMaterial(entity);
            entity.polygon.height = new Cesium.ConstantProperty(2);
            entity.polygon.extrudedHeight = new Cesium.ConstantProperty(4.2);
            entity.polygon.outline = new Cesium.ConstantProperty(true);
            entity.polygon.outlineColor = new Cesium.ConstantProperty(Cesium.Color.YELLOW); // 修改边界颜色为黄色
            entity.polygon.outlineWidth = new Cesium.ConstantProperty(10);

            // 获取属性并处理乡镇名称
            const properties = entity.properties?.getValue();
            const rawName = properties?.name || '未命名地块';
            const townshipKey = rawName.trim().replace(/\s+/g, ''); // 统一去除空格匹配

            // 设置标签 名称在上，数据在下
            entity.label = new Cesium.LabelGraphics({
              text: `${rawName}\n${townshipData.value[townshipKey] || '0'}`, // 使用换行符
              font: '18px Microsoft Yahei',
              fillColor: Cesium.Color.WHITE.withAlpha(1.0),
              outlineColor: new Cesium.Color(0.1, 0.1, 0.1, 0.8),
              outlineWidth: 3,
              style: Cesium.LabelStyle.FILL_AND_OUTLINE,
              verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
              horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
              pixelOffset: new Cesium.Cartesian2(0, -20),  // 调整偏移量适应两行文本
              heightReference: Cesium.HeightReference.RELATIVE_TO_GROUND, // 相对地面高度
              show: true
            });

            // 保持原有位置设置
            const centroid = properties?.centroid;
            const center = centroid && centroid.length >= 2
              ? Cesium.Cartesian3.fromDegrees(centroid[0], centroid[1])
              : Cesium.Cartesian3.fromDegrees(0, 0);
            entity.position = new Cesium.ConstantPositionProperty(center);
          }
        });
        // 加载数据源时保存实体
        allEntities = dataSource.entities.values;

        // 加载村信息
        await loadVillageInfo(viewer);

        return dataSource;
      } catch (error) {
        console.error('加载GeoJSON失败:', error);
        return null;
      }
    };

    // 加载村信息 - 修改：添加图标显示
    const loadVillageInfo = async (viewer: Cesium.Viewer) => {
      try {
        const villageData = await axios.get('public/static/geojson/411623cun.json'); // 假设村信息文件名为 village.json
        const features = villageData.data.features;

        features.forEach((feature: any) => {
          const properties = feature.properties;
          const coordinates = feature.geometry.coordinates;
          const villageName = properties.XZQMC;
          const villageId = properties.ID || Math.random().toString(36).substr(2, 9); // 使用ID或生成随机ID

          if (coordinates && villageName) {
            const position = Cesium.Cartesian3.fromDegrees(coordinates[0], coordinates[1]);

            const villageEntity = new Cesium.Entity({
              position: position,
              billboard: {
                image: 'public/static/imgs/village_icon.png', // 村庄图标路径，需要准备图标文件
                width: 24,
                height: 24,
                verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                scale: 1.0,
                color: Cesium.Color.WHITE,
                show: new Cesium.ConstantProperty(false) // 默认隐藏图标
              },
              label: {
                text: villageName,
                font: '14px Microsoft Yahei',
                fillColor: Cesium.Color.WHITE.withAlpha(1.0),
                outlineColor: new Cesium.Color(0.1, 0.1, 0.1, 0.8),
                outlineWidth: 3,
                style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                pixelOffset: new Cesium.Cartesian2(0, -30), // 调整偏移量，避免与图标重叠
                heightReference: Cesium.HeightReference.RELATIVE_TO_GROUND,
                show: new Cesium.ConstantProperty(false) // 默认隐藏村名称
              },
              properties: {
                id: villageId,
                name: villageName,
                type: 'village'
              }
            });

            viewer.entities.add(villageEntity);
            villageEntities.push(villageEntity);
          }
        });
      } catch (error) {
        console.error('加载村信息失败:', error);
      }
    };

    wellDataSource = new Cesium.CustomDataSource("wellPoints");
    const backButton = document.createElement('button'); // 创建返回按钮
    //机井信息面板样式
    const infoPanel = document.createElement('div');
    infoPanel.id = 'wellInfoPanel';
    infoPanel.style.cssText = `
        position: absolute;
    top: 20px;
    right: 20px;
    background: white;  // 修改为白色背景
    color: #333;       // 修改文字颜色为深灰色
    padding: 15px;     // 减少内边距
    border-radius: 8px;
    max-width: 2000px;
    display: none;
    z-index: 1000;
    border: 1px solid #ddd;  // 浅灰色边框
    height: 700px;
    box-sizing: border-box;`;  // 确保padding不影响总尺寸

    // 判断点是否在多边形内
    const isPointInPolygon = (point: [number, number], polygon: [number, number][]) => {
      let inside = false;
      for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
        const xi = polygon[i][0], yi = polygon[i][1];
        const xj = polygon[j][0], yj = polygon[j][1];

        const intersect = ((yi > point[1]) !== (yj > point[1])) &&
          (point[0] < (xj - xi) * (point[1] - yi) / (yj - yi) + xi);
        if (intersect) inside = !inside;
      }
      return inside;
    };

    // 在多边形内随机生成点
    const generateRandomPointInPolygon = (polygon: [number, number][]) => {
      let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
      for (const [x, y] of polygon) {
        minX = Math.min(minX, x);
        minY = Math.min(minY, y);
        maxX = Math.max(maxX, x);
        maxY = Math.max(maxY, y);
      }

      let point: [number, number];
      do {
        const x = minX + Math.random() * (maxX - minX);
        const y = minY + Math.random() * (maxY - minY);
        point = [x, y];
      } while (!isPointInPolygon(point, polygon));

      return point;
    };

    // 增强的交互处理
    const initInteractions = (viewer: Cesium.Viewer) => {
      //跳转到商水县
      const position = Cesium.Cartesian3.fromDegrees(114.56685346381893, 33.456135643555825, 100000);
      viewer.camera.setView({
        destination: position,
        orientation: {
          heading: Cesium.Math.toRadians(0), // 正北方向
          pitch: Cesium.Math.toRadians(-85), // 俯视85度
          roll: 0 // 无翻滚
        }
      });

      viewer.dataSources.add(wellDataSource);

      // 返回按钮
      const initBackButton = () => {
        backButton.id = 'cesiumBackButton'; // 添加唯一ID
        backButton.textContent = '返回县区';
        backButton.style.position = 'absolute';
        backButton.style.top = '20px';
        backButton.style.left = '30px';
        backButton.style.zIndex = '1000';
        backButton.style.backgroundColor = '#3388ff'; // 背景色
        backButton.style.border = '2px solid #ffffff'; // 边框样式
        backButton.style.borderRadius = '5px'; // 圆角
        backButton.style.padding = '8px 15px'; // 内边距
        backButton.style.color = 'black'; // 文字颜色
        backButton.style.fontWeight = 'bold'; // 字体加粗
        backButton.style.cursor = 'pointer'; // 手型光标
        backButton.style.boxShadow = '0 2px 5px rgba(0,0,0,0.2)'; // 添加阴影
        backButton.style.display = 'none'; // 默认隐藏
        viewer.container.appendChild(backButton);
        //返回按钮监听
        backButton.addEventListener('click', () => {
          // 恢复县级图层
          dataSource?.entities.values.forEach(e => e.show = true);
          // 清除井点数据
          wellDataSource.entities.removeAll();
          //恢复县级视角
          const position = Cesium.Cartesian3.fromDegrees(114.56685346381893, 33.456135643555825, 100000);
          viewer.camera.setView({
            destination: position,
            orientation: {
              heading: Cesium.Math.toRadians(0), // 正北方向
              pitch: Cesium.Math.toRadians(-85), // 俯视85度
              roll: 0 // 无翻滚
            }
          });
          allEntities.forEach(entity1 => {
            // 高亮被点击乡镇的边界
            if (entity1.polygon) {
              entity1.polygon.fill = true;       // 关闭填充
              entity1.polygon.outline = true;     // 显示轮廓线
              entity1.polygon.outlineColor = Cesium.Color.YELLOW; // 设置高亮颜色
            }
          });
          // 隐藏返回按钮
          backButton.style.display = 'none';
          closeInfoPanel();
          // 隐藏村名称和图标
          villageEntities.forEach(entity => {
            if (entity.label) { // 添加空值检查
              entity.label.show = new Cesium.ConstantProperty(false);
            }
            if (entity.billboard) {
              entity.billboard.show = new Cesium.ConstantProperty(false);
            }
          });
        });
      };

      viewer.container.appendChild(infoPanel);

      handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);

      // 带节流的鼠标移动事件
      let lastMove = 0;
      handler.setInputAction((movement: Cesium.ScreenSpaceEventHandler.MotionEvent)  => {
        const now = Date.now();
        if (now - lastMove < 50) return;
        lastMove = now;

        const picked = viewer.scene.pick(movement.endPosition);
        const newEntity = picked?.id instanceof Cesium.Entity ? picked.id : null;

        if (newEntity !== highlightEntity) {
          // 强制更新标签显示
          [highlightEntity, newEntity].forEach(entity => {
            if (entity?.label?.text instanceof Cesium.CallbackProperty) {
              entity.label.text.getValue(viewer.clock.currentTime);
            }
          });
          highlightEntity = newEntity;
        }
      }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

      // 保持原有点击事件 - 修改：增加村庄图标点击处理
      handler.setInputAction(async (click: Cesium.ScreenSpaceEventHandler.PositionedEvent) => {
        const picked = viewer.scene.pick(click.position);

        // 优先处理井点点击事件
        if (picked?.id?.entityCollection?.owner === wellDataSource) {
          const wellInfo = picked.id.properties.getValue();
          fetchGetQR(wellInfo.wellNumber);
          const position = picked.id.position.getValue(Cesium.JulianDate.now()); // 获取当前时间的位置
          // 转换为屏幕坐标
          const screenPosition = Cesium.SceneTransforms.worldToWindowCoordinates(
            viewer.scene,
            position
          );
          console.log('信息:', wellInfo);
          // 判断转换是否成功
          if (screenPosition) {
            updateInfoPanelPosition(screenPosition, viewer, position);
            showWellInfo(wellInfo);
          }
          return;
        }
        // 处理村庄图标点击事件
        else if (picked?.id instanceof Cesium.Entity && picked.id.properties?.getValue()?.type === 'village') {
          const villageInfo = picked.id.properties.getValue();
          const position = picked.id.position.getValue(Cesium.JulianDate.now());
          const screenPosition = Cesium.SceneTransforms.worldToWindowCoordinates(
            viewer.scene,
            position
          );
          if (screenPosition) {
            updateInfoPanelPosition(screenPosition, viewer, position);
            const response = await fetch(`/api/farmwell/ghy/geIdtBytown?town=${encodeURIComponent(villageInfo.name)}`, {
              method: 'GET',
              headers: {
                'Content-Type': 'application/json'
              },

            });
            if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
            // 获取完整响应对象
            const responseData = await response.json();
            // 提取实际井点数据数组
            const dataInfo = responseData.data; // 从rows字段获取数组
            villageInfo.id = dataInfo
            // 调用新的村庄信息显示方法
            showCountryWellInfo(villageInfo);
          }
          return;
        }
        else {
          closeInfoPanel();
          if (picked?.id instanceof Cesium.Entity) {
            const entity = picked.id;
            const properties = entity.properties?.getValue();

            // 隐藏信息面板
            infoPanel.style.display = 'none';
            // 遍历所有实体，隐藏非点击区域的填充和边界
            allEntities.forEach(entity1 => {
              if (entity1 === entity) {
                // 高亮被点击乡镇的边界
                if (entity1.polygon) {
                  entity1.polygon.fill = false;       // 关闭填充
                  entity1.polygon.outline = true;     // 显示轮廓线
                  entity1.polygon.outlineColor = Cesium.Color.YELLOW; // 设置高亮颜色
                }
              } else {
                // 隐藏其他区域的填充和边界
                if (entity1.polygon) {
                  entity1.polygon.fill = false;       // 关闭填充
                  entity1.polygon.outline = false;    // 隐藏轮廓线
                }
                if (entity1.polyline) {
                  entity1.show = false;              // 隐藏折线边界（如果有独立边界层）
                }
              }
            });
            //跳转坐标
            const position = Cesium.Cartesian3.fromDegrees(properties.centroid[0], properties.centroid[1], 10000);
            //跳转到点击乡镇
            viewer.camera.setView({
              destination: position,
              orientation: {
                heading: Cesium.Math.toRadians(0), // 正北方向
                pitch: Cesium.Math.toRadians(-85), // 俯视85度
                roll: 0 // 无翻滚
              }
            });

            fetchPlotDetail(properties.name, properties, entity.polygon.hierarchy.getValue().positions);

            // 在跳转坐标后添加飞行动画
            viewer.camera.flyTo({
              destination: position,
              orientation: {
                heading: Cesium.Math.toRadians(0),
                pitch: Cesium.Math.toRadians(-85),
                roll: 0
              },
              duration: 2 // 2秒飞行动画
            });
            initBackButton();
            backButton.style.display = 'block';
            // 显示村名称和图标
            villageEntities.forEach(entity => {
              if (entity.label) { // 添加空值检查
                entity.label.show = new Cesium.ConstantProperty(true);
              }
              if (entity.billboard) {
                entity.billboard.show = new Cesium.ConstantProperty(true);
              }
            });
          }

        }
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    };

    interface EntityProperties {
      centroid: [number, number]; // 假设 centroid 是一个包含两个数字的数组，表示经纬度
      // 如果还有其他属性，可以在这里继续添加
      // 例如：
      // name: string;
    }

    //请求乡镇机井信息列表
    const fetchPlotDetail = async (town: string, properties: EntityProperties, polygonPositions: Cesium.Cartesian3[]) => {
      try {
        // 发起请求
        const response = await fetch(`/api/farmwell/well/getListByTown?county=${encodeURIComponent(town)}`, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json'
          },

        });
        if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
        // 获取完整响应对象
        const responseData = await response.json();
        // 提取实际井点数据数组
        const wellDataArray = responseData.data; // 从rows字段获取数组
        WellInfos = wellDataArray;

        console.log(wellDataArray);
        wellDataSource.entities.removeAll();

        const polygon = polygonPositions.map(pos => {
          const cartographic = Cesium.Cartographic.fromCartesian(pos);
          return [Cesium.Math.toDegrees(cartographic.longitude), Cesium.Math.toDegrees(cartographic.latitude)] as [number, number];
        });

        // 动态添加新点
        wellDataArray.forEach((well: any) => {
          const [lon, lat] = generateRandomPointInPolygon(polygon);
          wellDataSource.entities.add({
            position: Cesium.Cartesian3.fromDegrees(lon, lat, 100),
            billboard: {
              image: 'static/imgs/1.png',
              width: 12,   // 图标宽度（像素）
              height: 15,  // 图标高度（像素）
              color: Cesium.Color.WHITE.withAlpha(0.9), // 颜色叠加（可选）
              verticalOrigin: Cesium.VerticalOrigin.BOTTOM // 使图标底部对齐坐标
            },
            properties: well // 绑定完整数据
          });
        });

      } catch (error) {
        console.error('数据获取失败:', error);
      }
    };

    //按照机井编号获取二维码
    const fetchGetQR = async (wellNumber: string) => {
      try {
        // 发起请求
        const response = await fetch(`http://127.0.0.1:8080/farmwell/well/getQR/${wellNumber}`, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/octet-stream'
          },

        });
        if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);

        // 获取 blob 数据（适用于图片、文件等二进制内容）
        const data = await response.blob();

        //创建一个临时的 URL 指向这个 blob 对象
        QRblob = URL.createObjectURL(data);

      } catch (error) {
        console.error('二维码获取失败:', error);
      }
    };

    // 显示机井信息内容
    const showWellInfo = (wellInfo: any) => {
      infoPanel.innerHTML = `
    <h3 style="margin:0 0 10px 0; color: #8ac7ff">机井编号：${wellInfo.wellNumber || '无编号'}</h3>
    <div style="width:100%; height:calc(100% - 30px);">
      <iframe src="http://111.6.105.59:8114/faultReport?param=${wellInfo.id}"
              width="100%"
              height="100%"
              frameborder="0"
              style="border:none;"></iframe>
    </div>
  `;
      infoPanel.style.display = 'block';

      // 调用更新位置函数，确保面板居中
      updateInfoPanelPosition(new Cesium.Cartesian2(0, 0), cesiumRef?.viewer!, new Cesium.Cartesian3(0, 0, 0));
    };

    // 新增：显示村庄信息内容 - 修改：使用新的iframe URL
    const showCountryWellInfo = (villageInfo: any) => {
      console.log(villageInfo)
      infoPanel.innerHTML = `
    <h3 style="margin:0 0 10px 0; color: #8ac7ff">村庄：${villageInfo.name || '未命名'}</h3>
    <div style="width:100%; height:calc(100% - 40px); position: relative;">
      <iframe src="http://111.6.105.59:8114/country_faultReport?param=${villageInfo.id}"
              width="100%"
              height="100%"
              frameborder="0"
              style="border:none;"></iframe>
    </div>
  `;
      infoPanel.style.display = 'block';

      // 调用更新位置函数，确保面板居中
      updateInfoPanelPosition(new Cesium.Cartesian2(0, 0), cesiumRef?.viewer!, new Cesium.Cartesian3(0, 0, 0));
    };

    // 更新信息面板位置（居中显示）
    const updateInfoPanelPosition = (screenPos: Cesium.Cartesian2, viewer: Cesium.Viewer, position: Cesium.Cartesian3) => {
      // 视口尺寸
      const container = viewer.container;
      const viewportWidth = container.clientWidth;
      const viewportHeight = container.clientHeight;

      // 面板尺寸
      const panelWidth = 1200; // 固定宽度
      const panelHeight = 700; // 固定高度

      // 设置面板尺寸
      infoPanel.style.width = `${panelWidth}px`;
      infoPanel.style.height = `${panelHeight}px`;

      // 计算居中位置
      const left = (viewportWidth - panelWidth) / 2;
      const top = (viewportHeight - panelHeight) / 2;

      // 应用位置
      infoPanel.style.left = `${left}px`;
      infoPanel.style.top = `${top}px`;

      // 移除旧的相机监听器（不再需要跟随位置变化）
      if (cameraListener) {
        cameraListener();
        cameraListener = null;
      }
    };

    // 关闭信息面板函数
    const closeInfoPanel = () => {
      infoPanel.style.display = 'none';
      // 移除相机监听器
      if (cameraListener) {
        cameraListener();
        cameraListener = null;
      }
      // 释放QR blob资源
      if (QRblob) {
        URL.revokeObjectURL(QRblob);
        QRblob = null;
      }
    };

    // 初始化
    const init = async () => {
      if (!cesiumRef?.viewer) return;

      const viewer = cesiumRef.viewer;
      const geoJsonSource = await loadGeoJson(viewer);

      if (geoJsonSource) {
        viewer.jt?.layerManager.registerLayer('farmland-layer', {
          show: true,
          zIndex: 0,
          setShowCb: (show: boolean) => {
            geoJsonSource.entities.values.forEach(e => e.show = show);
          },
          collection: geoJsonSource
        });
      }

      initInteractions(viewer);
    };

    onMounted(() => {
      init();
    });

    onUnmounted(() => {
      handler?.destroy();
      if (dataSource && cesiumRef?.viewer) {
        cesiumRef.viewer.dataSources.remove(dataSource);
      }
      // 释放所有资源
      closeInfoPanel();
    });

    return {};
  }
});
</script>
